package deepseek

import (
	"bytes"
	"encoding/json"
	"io"
	"net/http"
	"strings"

	"mall/common/globalkey"

	"github.com/friendsofgo/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

const (
	URL           = "https://api.deepseek.com/chat/completions"
	PRIVATEKEY    = "sk-41c27a98803144339bcb9b2bd1031a3d"
	MODEL         = "deepseek-chat"
	SYSTEMCONTENT = "你是一位香水行业的专家，用户将提供一系列问题，你的回答应当简明扼要。"
)

func AskDeepSeekAI(contents []string, contentType uint32) (map[string]any, error) {
	headers := map[string]string{
		"Content-Type":  "application/json",
		"Authorization": "Bearer " + PRIVATEKEY,
	}

	// 请求的 Body
	var messages = []map[string]string{
		{
			"role":    "system",
			"content": SYSTEMCONTENT,
		},
	}
	var m = make(map[string]any)
	if contentType == globalkey.DeepseekContentTypeDialogue {
		if len(contents)%2 == 0 {
			return nil, errors.New("AskDeepSeekAI contents num is even numbers,Incorrect data!")
		}

		//多轮对话上下文拼接  system、user、assistant、user、assistant ···
		for i, v := range contents {
			//单数为问，双数为答
			if i%2 == 0 {
				messages = append(messages, map[string]string{
					"role":    "user",
					"content": v,
				})
			} else {
				messages = append(messages, map[string]string{
					"role":    "assistant",
					"content": v,
				})
			}
		}

		m = map[string]any{
			"model":             MODEL,
			"max_tokens":        1000, //回答最多300字
			"frequency_penalty": 1,
			"presence_penalty":  1,
			"temperature":       0.2,
			"messages":          messages,
			"stream":            false,
		}
	}
	if contentType == globalkey.DeepseekContentTypeDefault {
		if contents != nil && len(contents) > 0 {
			messages = append(messages, map[string]string{
				"role":    "user",
				"content": contents[0],
			})
			m = map[string]any{
				"model":             MODEL,
				"max_tokens":        1000, //回答最多300字
				"frequency_penalty": 1,
				"presence_penalty":  1,
				"temperature":       0.2,
				"messages":          messages,
				"stream":            false,
			}
		}
	}

	// 将请求 Body 转换为 JSON
	body, err := json.Marshal(m)
	if err != nil {
		return nil, err
	}

	// 创建 HTTP 请求
	req, err := http.NewRequest("POST", URL, bytes.NewBuffer(body))
	if err != nil {
		return nil, err
	}

	// 设置请求头
	for key, value := range headers {
		req.Header.Set(key, value)
	}

	// 发送请求并获取响应
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}

	if resp.Status != "200 OK" {
		return nil, errors.New("AskDeepSeekAI resp.Status not is 200 OK,Request failed!")
	}

	defer resp.Body.Close()
	var buffer bytes.Buffer
	_, err = io.Copy(&buffer, resp.Body)
	if err != nil {
		logx.Errorw("[DeepSeek] Error reading response:", logx.Field("detail", err.Error()))
		return nil, err
	}
	dsResp := map[string]any{}
	if err = json.Unmarshal(buffer.Bytes(), &dsResp); err != nil {
		logx.Errorw("[DeepSeek] Error json.Unmarshal:", logx.Field("detail", err.Error()))
		return nil, err
	}

	return dsResp, nil
}

func GetContentLabel(content string) []string {
	//defer func() {
	//	wg.Done()
	//}()
	//询问deepseek 获取标签
	var labels []string
	aiResp, err := AskDeepSeekAI([]string{content + " 请从 木质香,花香调,绅士风,优雅感,商务款,约会香,烟草香,暖男风,安全感,乌木调,焚香感,持久款,美食调,草本香,广藿香,麝香调,白花香,清新感,脂粉气,中性香,自然风,暖香,伪体香,蜜瓜香,清新调 中选出三个词作为这段话的标签使用，词语与词语之间用英文逗号隔开，方便处理,请严格按照要求回答！"}, globalkey.DeepseekContentTypeDefault)
	if err != nil {
		logx.Infow("DeferredInquireAiMq.execService AskDeepSeekAI err", logx.Field("detail", err.Error()))
	}
	if choices, ok := aiResp["choices"]; ok {
		for _, choice := range choices.([]any) {
			if msg, ok := choice.(map[string]any)["message"]; ok {
				var messageMap = msg.(map[string]any)
				var content string
				if c, ok := messageMap["content"]; ok {
					content = c.(string)
				}

				if len(content) > 0 {
					c := strings.Split(content, ",")
					labels = append(labels, c...)
				}
			}
		}
	}
	return labels
}
